package com.huiminpay.paymentagent.message;

import com.alibaba.fastjson.JSON;
import com.huiminpay.paymentagent.api.PayChannelAgentService;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;

public class PayConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    PayChannelAgentService agentService;
    @Autowired
    PayProducer payProducer;

    @Override
    public void onMessage(MessageExt messageExt) {
        //取出消息
        byte[] bytes = messageExt.getBody();
        String msg_json = new String(bytes);

        //转为对象
        PaymentResponseDTO responseDTO = JSON.parseObject(msg_json, PaymentResponseDTO.class);
        //商户订单号
        String outTradeNo = responseDTO.getOutTradeNo();
        //支付参数
        String param_json= String.valueOf(responseDTO.getContent());
        AliConfigParam aliConfigParam = JSON.parseObject(msg_json, AliConfigParam.class);

        //调代理服务查询支付结果
        PaymentResponseDTO result = agentService.queryPayOrderByAli(aliConfigParam, outTradeNo);
        //交易状态
        TradeStatus tradeState = result.getTradeState();

        //重试一定次数后,使用单独的逻辑进行处理
        //获取重试次数
        int reconsumeTimes = messageExt.getReconsumeTimes();
        if (reconsumeTimes>2) {
            //如果重试两次就不再重试了  使用另外的逻辑的单独处理
            //.....
            System.out.println("重试次数过多");
            return;
        }


        //如果交易状态未知或正在支付,就等会再查(消费重试)
        if (tradeState.equals(TradeStatus.UNKNOWN)||tradeState.equals(TradeStatus.USERPAYING)) {
            throw new RuntimeException("支付状态未知,等待重试");
        }
        //将结果消息发送到MQ中,由交易服务消费
        //.....
        payProducer.payResultotive(result);
    }
}
